package com.dingding.queue.queue.consumer.listener;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.queue.dto.business.BusinessRequestDTO;
import com.dingding.facade.user.service.IUserLoginFacade;

/**
 * 
 * @ClassName: BusinessMessageListener
 * @Description: 执行业务队列监听
 * @author yuHaiQing
 * @date 2016年8月11日 下午12:02:12
 * @since V2.4.0
 * 
 */
@Component("businessListener")
public class BusinessListener implements MessageListener {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "userLoginService")
	private IUserLoginFacade userLoginFacade;

	@Override
	public Action consume(Message message, ConsumeContext context) {
		return parseQueueData(new String(message.getBody()));
	}

	/**
	 * 
	 * 从队列中读取数据
	 * 
	 * @Title: parseQueueData 
	 * @param queueData 队列中读取的数据 
	 * @since V2.4.0
	 * @author YHQ
	 * 
	 */
	public Action parseQueueData(String queueData) {

		log.info("推送消息,原生队列中的消息内容为：" + queueData);

		BusinessRequestDTO businessRequestDTO = null;

		try {
			businessRequestDTO = JSONUtil.parseObject(queueData, BusinessRequestDTO.class);
		} catch (Exception e) {
			log.info("解析队列中的JSON数据出现问题！", e);
			return Action.CommitMessage;
		}

		// 推送
		boolean flag = userLoginFacade.addPushNumber(businessRequestDTO.getUserId());

		if (flag) {
			return Action.CommitMessage;
		} else {
			return Action.ReconsumeLater;
		}

	}

}
